﻿using DFGK_WMS.IRepository;
using DFGK_WMS.Model.DTO;
using DFGK_WMS.Model.Enum;
using DFGK_WMS.Model.Models;
using DFGK_WMS.WebAPI.AttributeFile;
using DFGK_WMS.WebAPI.Controllers.Result;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Hosting;
using NetTaste;
using NPOI.HSSF.UserModel;
using NPOI.SS.Formula.Functions;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using OfficeOpenXml;
using System;
using System.Data;
using System.Security.Claims;
using System.Security.Cryptography;
using static NPOI.HSSF.Util.HSSFColor;

namespace DFGK_WMS.WebAPI.Controllers.入库
{
    /// <summary>
    /// 入库
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class TReceivingOrderDetailController : ControllerBase
    {
        private readonly ILogRepository logService;
        private readonly IWebHostEnvironment environment;
        private readonly IConfiguration configuration;

        public TReceivingOrderDetailController(ITReceivingOrderDetailRepository tReceiving, ITReceivingGoodsDetailRepository tReceivingGoodsDetailRepository, ILogRepository logService, IWebHostEnvironment environment, IConfiguration configuration)
        {

            TReceiving = tReceiving;
            TReceivingGoodsDetailRepository = tReceivingGoodsDetailRepository;
            this.logService = logService;
            this.environment = environment;
            this.configuration = configuration;
        }

        public ITReceivingOrderDetailRepository TReceiving { get; }
        public ITReceivingGoodsDetailRepository TReceivingGoodsDetailRepository { get; }


        /// <summary>
        /// 添加数据至sqlite
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>

        [HttpPost]
        public IActionResult AddSqliteDetail(GroupReceivingOrderDto item)
        {
            if (item == null)
            {
                return Ok(BaseResult.Result("400", "请求参数为空"));
            }
            var list = TReceiving.AddSqliteDetail(item, out var message);
            if (list)
            {
                return Ok(BaseResult.Result(true, "添加成功！", "200"));
            }
            return Ok(BaseResult.Result(false, message, "500"));
        }

        /// <summary>
        /// 读取sqlite数据
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetReceivingOrderDtos()
        {
            var list = TReceiving.GetReceivingOrderDtos();
            if (list != null || list.Count <= 0)
            {
                return Ok(BaseResult.Result(list, "查询成功！", "200"));
            }
            return Ok(BaseResult.Result(false, "查询失败！", "500"));
        }

        /// <summary>
        /// 入库后增库存
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult SubmitReceiving()
        {
            var list = TReceiving.SubmitReceiving(out var message);
            if (list)
            {
                return Ok(BaseResult.Result(list, "增加库存成功！", "200"));
            }
            return Ok(BaseResult.Result(false, message, "500"));
        }


        #region 已弃用方法
        #region 添加入库弃用
        ///// <summary>
        ///// 添加入库
        ///// </summary>
        ///// <param name="m"></param>
        ///// <returns></returns>
        //[HttpPost]
        //[HttpIdempotent(WaitMillisecond = 10000, CacheMillisecond = 3000)]
        //public IActionResult AddTReceivingOrderDetail(TReceivingOrderDetail m)
        //{
        //    string message = "";
        //    if(m.Qty<=0)
        //    {
        //        return Ok(BaseResult.Result("400", "入库数量不能为0"));
        //    }
        //    var rule = TReceiving.AddTReceivingOrderDetail(m,out message);
        //    if (rule)
        //    {
        //        string uname = HttpContext.User.FindFirstValue("UserName");
        //        string runame = HttpContext.User.FindFirstValue("RealName");
        //        int uid = Convert.ToInt32(HttpContext.User.FindFirstValue("Id"));
        //        string? ip = HttpContext.Connection.RemoteIpAddress?.ToString();
        //        TLog logg = new TLog();
        //        logg.LogType = 1;
        //        logg.ActionType = 4;
        //        logg.ModuleName = "入库管理";
        //        logg.UserName = uname;
        //        logg.RealName = runame;
        //        logg.UserId = uid;
        //        logg.Description = uname + "创建了入库单" + m.OrderSn;
        //        //获取前端IP地址
        //        logg.Ipaddress = ip;

        //        logService.AddTLod(logg);
        //        return Ok(BaseResult.Result(true, "添加成功", "200"));
        //    }
        //    return Ok(BaseResult.Result(false, message, "500"));
        //}
        #endregion

        #region 修改入库弃用
        ///// <summary>
        ///// 修改
        ///// </summary>
        ///// <param name="m"></param>
        ///// <returns></returns>
        //[HttpPut]
        //public IActionResult UpdTReceivingOrderDetail(TReceivingOrderDetail m)
        //{
        //    if (m.Id <= 0)
        //    {
        //        return Ok(BaseResult.Result("400", "Id有误！"));
        //    }
        //    if (m.Qty <= 0)
        //    {
        //        return Ok(BaseResult.Result("400", "入库数量不能为0"));
        //    }
        //    //if(m.Status!=0)
        //    //{
        //    //    return Ok(BaseResult.Result("200", "只有状态为创建的入库单才能修改"));
        //    //}
        //    string message = "";
        //    var rule = TReceiving.UpdTReceivingOrderDetail(m, out message);
        //    if (rule)
        //    {
        //        string uname = HttpContext.User.FindFirstValue("UserName");
        //        string runame = HttpContext.User.FindFirstValue("RealName");
        //        int uid = Convert.ToInt32(HttpContext.User.FindFirstValue("Id"));
        //        string? ip = HttpContext.Connection.RemoteIpAddress?.ToString();
        //        TLog logg = new TLog();
        //        logg.LogType = 1;
        //        logg.ActionType = 6;
        //        logg.ModuleName = "入库管理";
        //        logg.UserName = uname;
        //        logg.RealName = runame;
        //        logg.UserId = uid;
        //        logg.Description = uname + "修改了入库单" + m.OrderSn;
        //        //获取前端IP地址
        //        logg.Ipaddress = ip;

        //        logService.AddTLod(logg);
        //        return Ok(BaseResult.Result(true, "修改成功", "200"));
        //    }
        //    return Ok(BaseResult.Result(false, message, "500"));
        //}
        #endregion

        #region 显示入库单弃用
        ///// <summary>
        ///// 显示入库单列表(弃用)
        ///// </summary>
        ///// <param name="billType"></param>
        ///// <param name="status"></param>
        ///// <param name="warehouseid"></param>
        ///// <param name="pageIndex"></param>
        ///// <param name="pageSize"></param>
        ///// <param name="totalCount"></param>
        ///// <returns></returns>
        //[HttpGet]
        //public IActionResult GetReceivingOrderDetailList(string? orderSn, int billType, int status, int warehouseid, int pageIndex, int pageSize)
        //{
        //    if (pageIndex <= 0 || pageSize <= 0)
        //    {
        //        return Ok(BaseResult.Result("400", "分页参数有误！"));
        //    }
        //    int totalCount;

        //    var list = TReceiving.GetReceivingOrderDetailList(orderSn, billType, status, warehouseid, pageIndex, pageSize, out totalCount);

        //    if (list != null)
        //    {
        //        return Ok(BaseResult.Result(list, "查询成功！", "200", totalCount));
        //    }
        //    return Ok(BaseResult.Result(null, "查询失败！", "500", 0));
        //}
        #endregion

        #region 根据Id获取对象弃用
        ///// <summary>
        ///// 根据Id获取对象
        ///// </summary>
        ///// <param name="rid"></param>
        ///// <returns></returns>
        //[HttpGet]
        //public IActionResult GetTReceivingOrderDetailById(int rid)
        //{
        //    if (rid <= 0)
        //    {
        //        return Ok(BaseResult.Result("400", "Id有误！"));
        //    }
        //    var mobj = TReceiving.GetTReceivingOrderDetailById(rid);
        //    if (mobj != null)
        //    {
        //        return Ok(BaseResult.Result(mobj, "获取成功", "200"));
        //    }
        //    return Ok(BaseResult.Result(null, "获取失败！", "500"));
        //}
        #endregion
        #endregion

        /// <summary>
        /// 文件下载
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult FileDownload()
        {
            string SourceFile = configuration["SourceFile"];
            string DestinationFolder = configuration["DestinationFolder"];
            var IsOK = TReceiving.FileDownload(SourceFile, DestinationFolder);
            if (IsOK)
            {
                return Ok(BaseResult.Result(true, "移动成功！", "200"));
            }
            return Ok(BaseResult.Result(false, "移动失败！", "500"));
        }

        /// <summary>
        /// 添加入库
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        [HttpPost]
        [HttpIdempotent(WaitMillisecond = 10000, CacheMillisecond = 3000)]
        public IActionResult AddTReceivingOrderDetail(GroupReceivingOrderDto m)
        {
            string message = "";
            foreach (var item in m.childrenReceivingOrders)
            {
                if (item.ReceivedQty <= 0)
                {
                    return Ok(BaseResult.Result("400", "入库数量不能为0"));
                }
            }

            var isValidate = TReceiving.Validate(m,out string msg);
            if(!isValidate)
            {
                return Ok(BaseResult.Result(false, msg, "500"));

            }

            string uname = HttpContext.User.FindFirstValue("UserName");
            int uid = Convert.ToInt32(HttpContext.User.FindFirstValue("Id"));
            m.NowUserId = uid;
            m.NowUserName = uname;
            var rule = TReceiving.AddTReceivingOrderDetail(m, out message);

            if (rule)
            {
                string runame = HttpContext.User.FindFirstValue("RealName");
                string? ip = HttpContext.Connection.RemoteIpAddress?.ToString();
                TLog logg = new TLog();
                logg.LogType = 1;
                logg.ActionType = 4;
                logg.ModuleName = "入库管理";
                logg.UserName = uname;
                logg.RealName = runame;
                logg.UserId = uid;
                logg.Description = uname + "创建了入库单" + m.OrderSn;
                //获取前端IP地址
                logg.Ipaddress = ip;

                logService.AddTLod(logg);
                return Ok(BaseResult.Result(true, "添加成功", "200"));
            }
            return Ok(BaseResult.Result(false, message, "500"));
        }

        /// <summary>
        /// 修改入库
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        [HttpPut]
        [HttpIdempotent(WaitMillisecond = 10000, CacheMillisecond = 3000)]
        public IActionResult UpdTReceivingOrderDetail(GroupReceivingOrderDto m)
        {
            string message = "";

            foreach (var item in m.childrenReceivingOrders)
            {
                if (item.ReceivedQty <= 0)
                {
                    return Ok(BaseResult.Result("400", "入库数量不能为0"));
                }
            }
            string uname = HttpContext.User.FindFirstValue("UserName");
            int uid = Convert.ToInt32(HttpContext.User.FindFirstValue("Id"));
            m.NowUserId = uid;
            m.NowUserName = uname;
            var rule = TReceiving.UpdTReceivingOrderDetail(m, out message);
            if (rule)
            {
                string runame = HttpContext.User.FindFirstValue("RealName");
                string? ip = HttpContext.Connection.RemoteIpAddress?.ToString();
                TLog logg = new TLog();
                logg.LogType = 1;
                logg.ActionType = 4;
                logg.ModuleName = "入库管理";
                logg.UserName = uname;
                logg.RealName = runame;
                logg.UserId = uid;
                logg.Description = uname + "创建了入库单" + m.OrderSn;
                //获取前端IP地址
                logg.Ipaddress = ip;

                logService.AddTLod(logg);
                return Ok(BaseResult.Result(true, "修改成功", "200"));
            }
            return Ok(BaseResult.Result(false, message, "500"));
        }

        /// <summary>
        /// 修改状态
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        [HttpPut]
        public IActionResult UpdTReceivingOrderDetaState(ReceivingOrderDetailDto m)
        {
            string message = "";
            string uname = HttpContext.User.FindFirstValue("UserName");
            string runame = HttpContext.User.FindFirstValue("RealName");
            int uid = Convert.ToInt32(HttpContext.User.FindFirstValue("Id"));
            m.NowUserId = uid;
            m.NowUserRealName = runame;
            m.NowUserName = uname;
            bool IsOK = TReceiving.UpdTReceivingOrderDetaState(m);
            //拿到刚审核的字段
            var robj = TReceiving.GetGroupReceivingOrderDtoByOrdersn(m.OrderSN);
            if (robj != null && robj.State == 2)
            {
                var AddSqlite = TReceiving.AddSqliteDetail(robj, out message);
                if (!AddSqlite)
                {
                    return Ok(BaseResult.Result("400", message));
                }
            }
            if (IsOK)
            {
                return Ok(BaseResult.Result(true, "修改成功！", "200"));
            }
            return Ok(BaseResult.Result(false, message, "500"));
        }

        /// <summary>
        /// 删除入库单
        /// </summary>
        /// <param name="ordersn"></param>
        /// <returns></returns>
        [HttpDelete]
        public IActionResult DelTReceivingOrderDetail(string ordersn)
        {
            if (string.IsNullOrEmpty(ordersn) || ordersn.Length <= 0)
            {
                return Ok(BaseResult.Result("400", "Id有误！"));
            }
            bool IsOK = TReceiving.DelTReceivingOrderDetail(ordersn);
            if (IsOK)
            {
                return Ok(BaseResult.Result(true, "删除成功！", "200"));
            }
            return Ok(BaseResult.Result(false, "删除失败！", "500"));
        }

        /// <summary>
        /// 根据Id获取对象信息
        /// </summary>
        /// <param name="ordersn"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetGroupReceivingOrderDtoByOrdersn(string ordersn)
        {
            if (string.IsNullOrEmpty(ordersn) || ordersn.Length <= 0)
            {
                return Ok(BaseResult.Result("400", "编号有误！"));
            }
            var mobj = TReceiving.GetGroupReceivingOrderDtoByOrdersn(ordersn);
            if (mobj != null)
            {
                return Ok(BaseResult.Result(mobj, "获取成功", "200"));
            }
            return Ok(BaseResult.Result(null, "获取失败！", "501"));
        }

        /// <summary>
        /// 显示入库单列表
        /// </summary>
        /// <param name="orderSn"></param>
        /// <param name="billType"></param>
        /// <param name="status"></param>
        /// <param name="warehouseid"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetGroupReceivingOrderList(string? StartTime, string? EndTime, int? billType, int? status, int pageIndex, int pageSize)
        {
            if (pageIndex <= 0 || pageSize <= 0)
            {
                return Ok(BaseResult.Result("400", "分页参数有误！"));
            }
            int totalCount;
            string rolecode = HttpContext.User.FindFirstValue("RoleCode");
            var list = TReceiving.GetGroupReceivingOrderList(StartTime, EndTime, billType, status, rolecode, pageIndex, pageSize, out totalCount);

            if (list != null)
            {
                return Ok(BaseResult.Result(list, "查询成功！", "200", totalCount));
            }
            return Ok(BaseResult.Result(null, "查询失败！", "500", 0));
        }

        /// <summary>
        /// 枚举-入库单据状态
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetEmBillStatus()
        {
            var list = BaseEnum.GetCodeRulesList<EmBillStatus>();

            if (list != null)
            {
                return Ok(BaseResult.Result(list, "获取成功！", "200"));
            }
            return Ok(BaseResult.Result(null, "获取失败！", "500"));
        }

        /// <summary>
        /// 枚举-质量等级
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetQualityGradeEnum()
        {
            var list = BaseEnum.GetCodeRulesList<QualityGradeEnum>();

            if (list != null)
            {
                return Ok(BaseResult.Result(list, "获取成功！", "200"));
            }
            return Ok(BaseResult.Result(null, "获取失败！", "500"));
        }


        /// <summary>
        /// 枚举-入库单据类型
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetEmInBillType()
        {
            var list = BaseEnum.GetCodeRulesList<EmInBillType>();

            if (list != null)
            {
                return Ok(BaseResult.Result(list, "获取成功！", "200"));
            }
            return Ok(BaseResult.Result(null, "获取失败！", "500"));
        }
        MemoryStream ProcessExcelData()
        {
            //模块从表中读取的数据
            List<TReceivingOrderDetail> list = new List<TReceivingOrderDetail>();
            list = TReceiving.GetTReceivingOrderDetailExcel();
            // 已经读取出了正确的数据后
            //创建Excel对象把数据赋值到对象中
            IWorkbook workbook = new XSSFWorkbook(); // Excel对象
            ISheet sheet1 = workbook.CreateSheet("入库单");  // 创建Excel中的表对象
                                                          //表头
            IRow row0 = sheet1.CreateRow(0);  // 在sheet1表格中创建第0行
            row0.CreateCell(0).SetCellValue("单号"); // 在sheet1表格中第0行创建第0列，并且在给这个单元格赋值
            row0.CreateCell(1).SetCellValue("单据类型");
            row0.CreateCell(2).SetCellValue("单据状态");
            row0.CreateCell(3).SetCellValue("货主");
            row0.CreateCell(4).SetCellValue("物料名称");
            row0.CreateCell(5).SetCellValue("物料号");
            row0.CreateCell(6).SetCellValue("批次号");
            row0.CreateCell(7).SetCellValue("任务数量");
            row0.CreateCell(8).SetCellValue("实际收到数量");
            row0.CreateCell(9).SetCellValue("计量单位");
            row0.CreateCell(10).SetCellValue("包装数量");
            row0.CreateCell(11).SetCellValue("已组垛数量");
            row0.CreateCell(12).SetCellValue("有效期");
            row0.CreateCell(13).SetCellValue("生产日期");
            row0.CreateCell(14).SetCellValue("出厂日期");
            row0.CreateCell(15).SetCellValue("逻辑分区");
            row0.CreateCell(16).SetCellValue("订单来源");
            row0.CreateCell(17).SetCellValue("创建用户");
            row0.CreateCell(18).SetCellValue("创建时间");
            row0.CreateCell(19).SetCellValue("提交人");
            row0.CreateCell(20).SetCellValue("提交时间");
            row0.CreateCell(21).SetCellValue("审核(驳回)人");
            row0.CreateCell(23).SetCellValue("审核(驳回)时间");
            var rowIndex = 1;
            foreach (var item in list)
            {
                var Sta = "";//0-新建;1-已启动;2-作业中;3-已完成;4-强制完成;5-暂停;6-失效；7-异常
                if (item.Status == 0)
                {
                    Sta = "新建";
                }
                if (item.Status == 1)
                {
                    Sta = "已启动";
                }
                if (item.Status == 2)
                {
                    Sta = "作业中";
                }
                if (item.Status == 3)
                {
                    Sta = "已完成";
                }
                if (item.Status == 4)
                {
                    Sta = "强制完成";
                }
                if (item.Status == 5)
                {
                    Sta = "暂停";
                }
                if (item.Status == 6)
                {
                    Sta = "失效";
                }
                if (item.Status == 7)
                {
                    Sta = "异常";
                }
                var sType = "";//0-手动建单；1-ERP;2-MES;3-SAP
                if (item.SourceType == 0)
                {
                    sType = "手动建单";
                }
                if (item.SourceType == 1)
                {
                    sType = "ERP";
                }
                if (item.SourceType == 2)
                {
                    sType = "SAP";
                }
                IRow row = sheet1.CreateRow(rowIndex);
                row.CreateCell(0).SetCellValue(item.OrderSn);
                row.CreateCell(1).SetCellValue((double)item.BillType);
                row.CreateCell(2).SetCellValue(Sta);
                row.CreateCell(4).SetCellValue(item.MaterialName);
                row.CreateCell(5).SetCellValue(item.MaterialCode);
                row.CreateCell(7).SetCellValue((double)item.Qty);
                row.CreateCell(8).SetCellValue((double)item.ReceivedQty);
                row.CreateCell(9).SetCellValue(item.UnitName);
                row.CreateCell(9).SetCellValue((double)item.PackagedQty);
                row.CreateCell(9).SetCellValue((double)item.StackedQty);
                row.CreateCell(9).SetCellValue(item.ExpireDate.ToString());
                row.CreateCell(9).SetCellValue(item.ProductDate.ToString());
                row.CreateCell(9).SetCellValue(item.OutFactoryDate.ToString());
                row.CreateCell(9).SetCellValue(sType);
                row.CreateCell(9).SetCellValue(item.CreateUserName);
                row.CreateCell(9).SetCellValue(item.CreateDate);
                row.CreateCell(9).SetCellValue(item.SubmitUserName);
                row.CreateCell(9).SetCellValue(item.SubmitDate.ToString());
                row.CreateCell(9).SetCellValue(item.AuditUserName);
                row.CreateCell(9).SetCellValue(item.AuditDate.ToString());
                rowIndex++;
            }
            MemoryStream ms = new MemoryStream();
            workbook.Write(ms);

            return ms;
        }
        /// <summary>
        /// 下载入库单号
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public FileContentResult TreceExcel()
        {
            MemoryStream ms = ProcessExcelData();
            byte[] fileBytes = ms.ToArray();
            return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, "入库单.xlsx"); //关键语句
        }

        /// <summary>
        /// 生成条形码
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult BarCodeBuild(int id)
        {
            if (id <= 0)
            {
                return Ok(BaseResult.Result("400", "Id有误！"));
            }
            var receivingOrderDetail = TReceiving.GetTReceivingOrderDetailById(id);
            if (receivingOrderDetail is null)
            {
                return Ok(BaseResult.Result(null, "入库单不存在！", "500", 0));
            }
            if (!receivingOrderDetail.ReceivedQty.HasValue || receivingOrderDetail.ReceivedQty < 1)
            {
                return Ok(BaseResult.Result(null, "入库单数量必须大于1！", "500", 0));
            }
            int qty = Convert.ToInt32(receivingOrderDetail.ReceivedQty);

            var res = 0;
            if (TReceivingGoodsDetailRepository.GetReceivingGoodsDetailList(id) is not null)
            {
                res = TReceivingGoodsDetailRepository.GetReceivingGoodsDetailList(id).Count();
            }
            //if (res > 0 && res == qty)
            //{
            //    return Ok(BaseResult.Result(res, "", "200"));
            //}
            string baseBarCode = receivingOrderDetail.MaterialCode;
            int count = Convert.ToInt32(qty - res);
            List<TReceivingGoodsDetail> goodsDetailData = new List<TReceivingGoodsDetail>();
            //Random random = new Random();
            //int randomNumber = random.Next(100000, 999999);
            var UnitRulesL = TReceiving.GetUnitRulesList(receivingOrderDetail.UnitId);
            if (UnitRulesL != null)
            {
                decimal? ReceivingQty = receivingOrderDetail.Qty / UnitRulesL.frontValue;
                int PrintQty = (int)Math.Ceiling((decimal)ReceivingQty);
                for (int i = 0; i < PrintQty; i++)
                {
                    string barcode = baseBarCode/*+ randomNumber + ((res + i + 1) / 1000m).ToString("f3").Replace(".", "")*/;
                    goodsDetailData.Add(new TReceivingGoodsDetail()
                    {
                        Barcode = barcode,
                        BarcodeRange = "",
                        CreateDate = DateTime.Now,
                        IsSku = false,
                        SkuNum = 1,
                        OrderDetailId = receivingOrderDetail.Id,
                        Status = 0,
                    });
                }
            }
            else
            {
                for (int i = 0; i < count; i++)
                {
                    string barcode = baseBarCode/*+ randomNumber + ((res + i + 1) / 1000m).ToString("f3").Replace(".", "")*/;
                    goodsDetailData.Add(new TReceivingGoodsDetail()
                    {
                        Barcode = barcode,
                        BarcodeRange = "",
                        CreateDate = DateTime.Now,
                        IsSku = false,
                        SkuNum = 1,
                        OrderDetailId = receivingOrderDetail.Id,
                        Status = 0,
                    });
                }

            }

            if (!TReceivingGoodsDetailRepository.AddReceivingGoodsDetail(goodsDetailData))
            {
                return Ok(BaseResult.Result(null, "生成条码失败！", "500", 0));
            }
            var list = TReceiving.PrintReceiving(id);
            if (list == null || list.Count() <= 0)
            {
                return Ok(BaseResult.Result(null, "获取器材条码失败！", "200"));
            }


            //if ()
            //{
            return Ok(BaseResult.Result(list, "生成条码成功！", "200"));
            //   /// return Ok(BaseResult.Result(goodsDetailData, "生成条码成功！", "200"));
            //}

        }

        /// <summary>
        /// 导出编码
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GenerateExcel(int orderDetailId)
        {
            if (orderDetailId <= 0)
            {
                return Ok(BaseResult.Result("400", "Id有误！"));
            }
            var list = TReceivingGoodsDetailRepository.GetReceivingGoodsDetailList(orderDetailId);
            if (list.Count <= 0)
            {
                return Ok(BaseResult.Result(null, "导出失败！", "500", 0));
            }
            // 创建Excel文件和工作簿
            var package = new ExcelPackage();
            var worksheet = package.Workbook.Worksheets.Add("Sheet1");
            // 添加表头
            worksheet.Cells[1, 1].Value = "物料条码";
            // 添加数据行
            int row = 2;
            foreach (var item in list)
            {
                worksheet.Cells[row, 1].Value = item.Barcode;
                row++;
            }
            // 自适应列宽
            worksheet.Cells.AutoFitColumns();
            // 返回Excel文件
            var stream = new MemoryStream(package.GetAsByteArray());
            return new FileStreamResult(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
            {
                FileDownloadName = "货品条码" + list[0].Barcode + ".xlsx"
            };

        }

        /// <summary>
        /// 导入Excel
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult UploadUserInfo(IFormFile file)
        {
            try
            {
                // 检查文件是否为空
                if (file == null || file.Length == 0)
                {
                    return Ok(BaseResult.Result("400", "没有选择文件或文件为空"));
                }
                string message = "";
                var postFile = Request.Form.Files[0];
                string extName = Path.GetExtension(postFile.FileName);
                if (!new string[] { ".xls", ".xlsx" }.Contains(extName))
                {
                    return Ok(BaseResult.Result("400", "必须是Excel文件"));
                }
                string uname = HttpContext.User.FindFirstValue("UserName");
                int uid = Convert.ToInt32(HttpContext.User.FindFirstValue("Id"));
                MemoryStream ms = new MemoryStream();
                postFile.CopyTo(ms);
                ms.Position = 0;
                IWorkbook wb = null;
                if (extName.ToLower().Equals(".xls")) // 97-2003版本
                {
                    wb = new HSSFWorkbook(ms);
                }
                else
                {
                    wb = new XSSFWorkbook(ms); // 2007以上版本
                }

                ISheet sheet = wb.GetSheetAt(0);

                //总行数（0开始）
                int totalRow = sheet.LastRowNum;
                // 总列数（1开始）
                int totalColumn = sheet.GetRow(0).LastCellNum;
                bool chongfu = false;
                bool dbchongfu = false;
                List<ChildrenReceivingOrder> stuList = new();
                for (int i = 1; i <= totalRow; i++)
                {
                    
                    IRow row = sheet.GetRow(i);
                    string? MaterialCategoryName = row.GetCell(0)?.StringCellValue;
                    string? MaterialCategoryCode = row.GetCell(1)?.StringCellValue;
                    string? Name = row.GetCell(2)?.StringCellValue;
                    string? Code = row.GetCell(3)?.StringCellValue;
                    if (!TReceivingGoodsDetailRepository.CodeContainZ(Code,out string msg))
                    {
                        return Ok(BaseResult.Result(null, msg, "500"));
                    }
                    if(!TReceivingGoodsDetailRepository.CodeDoesItExist(Code,Name,out msg))
                    {
                        return Ok(BaseResult.Result(null, "导入表中第" + i + "行" + msg, "500"));
                    }
                    string? ModelSpec = "";
                    if (row.GetCell(4)?.CellType == CellType.String)
                    {
                        ModelSpec = row.GetCell(4)?.StringCellValue;
                    }
                    else
                    {
                        ModelSpec = row.GetCell(4)?.NumericCellValue.ToString();
                    }
                    string? QualityStateName = row.GetCell(5)?.StringCellValue;
                    string? UnitName = row.GetCell(6)?.StringCellValue;
                    int? ReceivedQty = (int?)row.GetCell(7)?.NumericCellValue;
                    decimal? ReceivePrice = (decimal?)row.GetCell(8)?.NumericCellValue;
                    decimal? ReceivedTotalPrice = (decimal?)row.GetCell(9)?.NumericCellValue;

                    //if (string.IsNullOrEmpty(Articlebarcode) || Articlebarcode == "0" || string.IsNullOrEmpty(Code) || Code == "0" || string.IsNullOrEmpty(Name) || string.IsNullOrEmpty(Shortname) || string.IsNullOrEmpty(UnitName) || string.IsNullOrEmpty(ModelSpec))
                    //{
                    //    continue;
                    //}
                    ////查询当前文件是否有重复的六九码
                    //chongfu = stuList.Where(x => x.Articlebarcode == Articlebarcode).Any();
                    //if (chongfu)
                    //{
                    //    message += Articlebarcode + "重复";
                    //    continue;
                    //}
                    ////查询库数据库中是否有重复的六九码
                    //dbchongfu = MaterialRepisotory.GetAll().Where(x => x.Articlebarcode == Articlebarcode).Any();
                    //if (dbchongfu)
                    //{
                    //    message += Articlebarcode + "重复";
                    //    continue;
                    //}



                    var user = new ChildrenReceivingOrder
                    {
                        Code = Code,
                        Name = Name,
                        ModelSpec = ModelSpec,
                        MaterialCategoryName = MaterialCategoryName,
                        MaterialCategoryCode = MaterialCategoryCode,
                        MakerialCategoryId = TReceivingGoodsDetailRepository.GetMaterialCategoryByCode(MaterialCategoryCode),
                        QualityState = QualityStateName == "新品" ? 0 : 1,
                        Price = ReceivePrice,
                        ReceivedQty = ReceivedQty,
                        TotalPrice = ReceivePrice * ReceivedQty,
                        ReceivedTotalPrice = ReceivedTotalPrice,
                        UnitId = TReceivingGoodsDetailRepository.GetUnitIdByUnitName(UnitName),
                        UnitName = UnitName,

                    };
                    stuList.Add(user);
                }
                if (stuList.Count <= 0)
                {
                    //message = "文件信息为空或别写字段为空！";
                    return Ok(BaseResult.Result(null, "导入失败！" + message, "500"));
                }
                wb.Close();

                return Ok(BaseResult.Result(stuList, "导入成功！" + message, "200"));
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 上传凭证
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> UploadFile(IFormFile file)
        {
            // 检查文件是否为空
            if (file == null || file.Length == 0)
            {
                return Ok(BaseResult.Result("400", "没有选择文件或文件为空"));
            }
            //检查文件类型
            //string fileExtension = Path.GetExtension(file.FileName).ToLower();
            //if (fileExtension != ".zip" && fileExtension != ".rar" && fileExtension != ".7z" && fileExtension != ".TAR")
            //{
            //    //return BadRequest("只允许上传 .jpg, .png 和 .gif 和.jfif 格式的文件");
            //    return Ok(BaseResult.Result("400", "只允许上传 .zip, .rar 和 .7z 和.TAR 格式的文件"));
            //}
            //// 检查文件大小
            //if (file.Length > 500 * 1024) // 单位为字节
            //{
            //    return Ok(BaseResult.Result("400", "上传的图片必须小于 500KB."));
            //}
            try
            {
                // 获取保存文件的根路径
                string uploadsFolder = Path.Combine(environment.WebRootPath, "file");
                // 创建文件夹（如果不存在）
                Directory.CreateDirectory(uploadsFolder);

                // 创建以当前日期命名的文件夹
                string currentDateFolder = DateTime.Now.ToString("yyyyMMdd");
                string folderPath = Path.Combine(uploadsFolder, currentDateFolder);
                Directory.CreateDirectory(folderPath);

                // 生成以当前时间命名的文件名
                string currentTime = DateTime.Now.ToString("yyyyMMddHHmmss");
                string fileExtension1 = Path.GetExtension(file.FileName).ToLower();
                //string fileName = $"{currentTime}{fileExtension1}";
                string fileName = file.FileName;

                // 保存文件到指定路径
                string filePath = Path.Combine(folderPath, fileName);
                using (var stream = new FileStream(filePath, FileMode.Create))
                {
                    await file.CopyToAsync(stream);
                }
                //本地
                //return Ok(BaseResult.Result("http://192.168.1.54:8889//file/" + currentDateFolder + "/" + fileName, fileName, "200"));
                return Ok(BaseResult.Result("localhost:8889//file/" + currentDateFolder + "/" + fileName, fileName, "200"));
                //云服务器
                //return Ok(BaseResult.Result("http://59.110.231.187:8887//file/" + currentDateFolder + "/" + fileName, fileName, "200"));
            }
            catch (Exception ex)
            {
                return StatusCode(500, $"文件上传失败：{ex.Message}");
            }
        }




        /// <summary>
        /// 获取商品条码
        /// </summary>
        /// <param name="OrdeSn"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult PrintReceiving(int OrderId)
        {
            var list = TReceiving.PrintReceiving(OrderId);
            if (list != null)
            {
                return Ok(BaseResult.Result(list, "获取器材条码成功！", "200"));
            }
            return Ok(BaseResult.Result(null, "获取器材条码失败！", "500"));
        }


        /// <summary>
        /// 获取装备数字
        /// </summary>
        /// <param name="OrdeSn"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult GetCategoryNumByCode(int categoryId)
        {
            var list = TReceiving.GetCategoryNumByCode(categoryId, out string message);
            if (list != null)
            {
                return Ok(BaseResult.Result(list, "查询成功！", "200"));
            }
            return Ok(BaseResult.Result(null, message, "500"));
        }

        /// <summary>
        /// 获取采购员角色人员
        /// </summary>
        /// <param name="OrdeSn"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetPurchaseRole()
        {
            var list = TReceiving.GetPurchaseRole();
            if (list != null)
            {
                return Ok(BaseResult.Result(list, "查询成功！", "200"));
            }
            return Ok(BaseResult.Result(null, "查询数据为空", "500"));
        }

        /// <summary>
        /// 选择仓位时带出数量
        /// </summary>
        /// <param name="cellCode"></param>
        /// <param name="materialCode"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetMsgByCellAndCode(string cellCode ,string materialCode)
        {
            var qty = TReceiving.GetMsgByCellAndCode(cellCode, materialCode);
            if (qty != 0)
            {
                return Ok(BaseResult.Result(qty, "查询成功！", "200"));
            }
            return Ok(BaseResult.Result(null, "未查询到数据", "500"));
        }
    }
}
